<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card">
        <el-tabs v-model="activeName">
          <el-tab-pane label="用户管理" name="first">
            <el-button type="primary" @click="addDialog">新增角色</el-button>
            <el-table :data="list" border style="margin-top: 20px; width: 100%">
              <el-table-column label="序号" type="index" width="50" />
              <el-table-column prop="name" label="角色名称" width="180" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="name" label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="editDialog(row.id)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delRole(row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              layout="prev, pager, next"
              style="float: right"
              :page-size="page.pagesize"
              :total="page.total"
              @current-change="currentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="配置管理" name="second">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              style="margin-bottom: 20px"
            />
            <el-form
              label-width="80px"
              :model="formData"
              style="width: 50%; margin: 0 auto"
            >
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" :disabled="true" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" :disabled="true" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" :disabled="true" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" :disabled="true" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        <!-- edit dialog -->
        <el-dialog v-if="showDialog" :title="titleText" :visible="showDialog" @close="btnCancel">
          <el-form
            ref="roleForm"
            :model="roleForm"
            :rules="rules"
            label-width="120px"
          >
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="roleForm.description" />
            </el-form-item>
          </el-form>
          <!-- 底部 -->
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" @click="btnCancel">取消</el-button>
              <el-button
                size="small"
                type="primary"
                @click="btnOK"
              >确定</el-button>
            </el-col>
          </el-row>
        </el-dialog>

        <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
          <!-- 权限是一颗树 -->
          <!-- 将数据绑定到组件上 -->
          <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
          <!-- id作为唯一标识 -->
          <el-tree
            ref="permTree"
            :data="permData"
            :props="defaultProps"
            :show-checkbox="true"
            :check-strictly="true"
            :default-expand-all="true"
            node-key="id"
          />
          <!-- 确定 取消 -->
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
              <el-button size="small" @click="btnPermCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  getCompanyInfo,
  getRoleList,
  delRole,
  addRole,
  getRoleDetail,
  updateRole,
  updateAssignPerm
} from '@/api/setting'
import { listToTree } from '@/utils'
import { getPermissionList } from '@/api/permission'
export default {
  data() {
    return {
      activeName: 'first',
      formData: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      page: {
        page: 1,
        pagesize: 2,
        total: 0
      },
      list: [],
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '此项不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '此项不能为空', trigger: 'blur' }
        ]
      },
      showPermDialog: false,
      permData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      permId: '',
      userId: ''
    }
  },
  computed: {
    titleText() {
      return this.roleForm.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getCompanyInfo()
    this.getRoleList()
  },
  methods: {
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.$store.getters.companyId)
      // console.log(this.formData)
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.list = rows
      this.page.total = total
    },
    currentChange(currPage) {
      // console.log(currPage)
      this.page.page = currPage
      this.getRoleList()
    },
    async delRole(id) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delRole(id)
        this.$message.success('删除成功')
        this.getRoleList()
        if (this.page.page > 1 && this.list.length === 1) {
          this.page.page--
        }
      } catch (error) {
        console.log(error)
      }
    },
    async editDialog(id) {
      this.showDialog = true
      this.roleForm = await getRoleDetail(id)
    },
    addDialog() {
      this.showDialog = true
    },
    btnCancel() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    async btnOK() {
      await this.$refs.roleForm.validate()
      if (this.roleForm.id) {
        await updateRole(this.roleForm)
        this.$message.success('修改角色成功')
      } else {
        await addRole(this.roleForm)
        this.$message.success('添加角色成功')
      }
      this.showDialog = false
      this.$refs.roleForm.resetFields()
      this.getRoleList()
    },
    async assignPerm(id) {
      // console.log(id)
      this.userId = id
      this.permData = listToTree(await getPermissionList(), '0')
      // console.log(this.permData)
      this.permId = (await getRoleDetail(id)).permIds
      this.showPermDialog = true
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(this.permId)
      })
      // console.log(this.permId)
    },
    btnPermCancel() {
      this.$refs.permTree.setCheckedKeys([])
      this.showPermDialog = false
    },
    async btnPermOK() {
      const permIds = this.$refs.permTree.getCheckedKeys()
      // console.log(permIds)
      const id = this.userId
      await updateAssignPerm({ id, permIds })
      this.$message.success('修改权限成功')
      this.btnPermCancel()
    }
  }
}
</script>

<style>
</style>
